package com.android.manghe.quickpay.activity

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.text.Editable
import android.text.TextUtils
import android.text.TextWatcher
import android.view.View
import androidx.core.content.ContextCompat
import com.android.base.frame.view.MVPActivity
import com.android.base.tools.DateTimeUtil
import com.android.base.tools.ToastUtil
import com.android.manghe.R
import com.android.manghe.common.model.BuyGoodShangMengZhiFuRes
import com.android.manghe.common.model.BuyMemberShangMengZhiFuRes
import com.android.manghe.quickpay.model.ShangMengCardNoInfo
import com.android.manghe.quickpay.presenter.PQuickPayDetail
import com.android.manghe.quickpay.view.CardListPopupView
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.core.BasePopupView
import com.lxj.xpopup.util.KeyboardUtils
import kotlinx.android.synthetic.main.activity_quick_pay_detail.*

class QuickPayDetailActivity : MVPActivity<PQuickPayDetail>() {


    override fun getLayoutId(): Int {
        return R.layout.activity_quick_pay_detail
    }

    override fun initData(savedInstanceState: Bundle?) {
        val tempBuyMemberShangMengZhiFuData = intent.getSerializableExtra("buyMemberShangMengZhiFuData")
        val tempBuyGoodShangMengZhiFuData = intent.getSerializableExtra("buyGoodShangMengZhiFuData")
        if (tempBuyMemberShangMengZhiFuData != null) {
            p.buyMemberShangMengData = tempBuyMemberShangMengZhiFuData as BuyMemberShangMengZhiFuRes.DataBean
            if (p.buyMemberShangMengData.paycode != null && !TextUtils.isEmpty(p.buyMemberShangMengData.paycode.binded_card_list)) {
                //有银行卡列表，显示银行卡信息
                p.cardList.addAll(Gson().fromJson<List<ShangMengCardNoInfo>>(
                        p.buyMemberShangMengData.paycode.binded_card_list,
                        object :
                                TypeToken<java.util.ArrayList<ShangMengCardNoInfo?>?>() {}.type
                ))
            }
        } else if (tempBuyGoodShangMengZhiFuData != null) {
            p.buyGoodShangMengData = tempBuyGoodShangMengZhiFuData as BuyGoodShangMengZhiFuRes.DataBean
            p.isSecondPay = intent.getBooleanExtra("secondPay", false)
            p.isBuyGood = true
            if (p.buyGoodShangMengData.paycode != null && !TextUtils.isEmpty(p.buyGoodShangMengData.paycode.binded_card_list)) {
                //有银行卡列表，显示银行卡信息
                p.cardList.addAll(Gson().fromJson<List<ShangMengCardNoInfo>>(
                        p.buyGoodShangMengData.paycode.binded_card_list,
                        object :
                                TypeToken<java.util.ArrayList<ShangMengCardNoInfo?>?>() {}.type
                ))
            }
        }
        titleBar.setToolbar("付款详情").setTitleAndStatusBgColor(R.color.white)
                .setLeftIcon(R.mipmap.icon_back_black).setRightIcon(R.mipmap.union_pay)
        tvName.setOnClickListener {
            layoutDetail.visibility =
                    if (layoutDetail.visibility == View.VISIBLE) View.GONE else View.VISIBLE
            ivArrowDown.visibility = if (layoutDetail.visibility == View.VISIBLE) View.GONE else View.VISIBLE
            tvName.isEnabled = false
        }
        tvTraceTime.setOnClickListener {
            ivArrowDown.visibility = View.VISIBLE
            layoutDetail.visibility = View.GONE
            tvName.isEnabled = true
        }
        btnNext.setOnClickListener {
            if (layoutFirstPay.visibility == View.VISIBLE) {
                //新增卡
                val cardNo = etCardNo.text.toString().replace(" ", "")
                if (TextUtils.isEmpty(cardNo)) {
                    ToastUtil.showLong(this, "请输入卡号")
                    return@setOnClickListener
                }
                p.next(cardNo)
            } else {
                //使用旧卡
                if (p.currentCardInfo == null) {
                    ToastUtil.showLong(this, "请选择银行卡")
                    return@setOnClickListener
                }
                toPayPage(p.currentCardInfo, p.currentCardInfo.card_no)
            }
        }
        layoutSecondPay.setOnClickListener {
            //弹出银行卡选择框
            showChooseCardDialog()
        }
        tvBoundCard.setOnClickListener {
//            if(p.currentCardInfo == null && p.cardList.isNotEmpty()){
//                p.currentCardInfo = p.cardList[0]
//            }
            showChooseCardDialog()
        }
        etCardNo.addTextChangedListener(object : TextWatcher {
            var beforeTextLength = 0
            var onTextLength = 0

            override fun beforeTextChanged(s: CharSequence, start: Int, count: Int,
                                           after: Int) {
                beforeTextLength = s.length
            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                val str = etCardNo!!.text.toString()
                setNextBtnEnable(str.isNotEmpty())
            }

            override fun afterTextChanged(s: Editable?) {
                val str = etCardNo!!.text.toString()
                onTextLength = str.length
                if (onTextLength > beforeTextLength) {
                    //输入
                    if (str.length % 5 == 0) {
                        etCardNo!!.setText(StringBuffer(str).insert(str.length - 1,
                                " ").toString())
                        etCardNo!!.setSelection(etCardNo!!.text.length)
                    }
                } else {
                    //删除
                    if (str.startsWith(" ")) {
                        etCardNo!!.setText(StringBuffer(str).delete(onTextLength - 1,
                                onTextLength).toString())
                        etCardNo!!.setSelection(etCardNo!!.text.length)
                    }
                }
            }
        })
//        EditTextUtil.disableCopyAndPaste(etCardNo)
        layoutFirstPay.visibility = if (!p.cardList.isNullOrEmpty()) View.GONE else View.VISIBLE
        layoutSecondPay.visibility = if (!p.cardList.isNullOrEmpty()) View.VISIBLE else View.GONE
        setNextBtnEnable(!p.cardList.isNullOrEmpty())
        if (!p.cardList.isNullOrEmpty()) {
            p.currentCardInfo = p.cardList[0]
            setCardDataView()
        }
        tvOrderPrice.text = "￥${if (p.isBuyGood) p.buyGoodShangMengData.order.order_amount else p.buyMemberShangMengData.order.amount}"
        tvOrderDesc.text = if (p.isBuyGood) p.buyGoodShangMengData.order.items[0].subject else p.buyMemberShangMengData.order.title
        tvTraceTime.text =
                DateTimeUtil.longToString(if (p.isBuyGood) p.buyGoodShangMengData.order.c_time.toLong() else p.buyMemberShangMengData.order.c_time.toLong(),
                        "yyyy-MM-dd HH:mm:ss")
    }

    private fun setNextBtnEnable(enable: Boolean){
        btnNext.isEnabled = enable
        btnNext.setTextColor(ContextCompat.getColor(this@QuickPayDetailActivity, if (!enable) R.color.white else R.color.colorFont33))
        btnNext.setBackgroundResource(if (!enable) R.drawable.btn_disable_round_selector else R.drawable.btn_primary_round_selector)
    }

    private fun setCardDataView() {
        tvBank.text = p.currentCardInfo.bank_name
        tvCardNo.text = "****${p.currentCardInfo.card_no}"
    }

    private var popupDialog: BasePopupView? = null
    private var cardPopupView: CardListPopupView? = null
    private fun showChooseCardDialog() {
        KeyboardUtils.hideSoftInput(etCardNo)
        if (!p.cardList.isNullOrEmpty()) {
            p.currentCardInfo = p.cardList[0]
        }
        cardPopupView = CardListPopupView(this, p.cardList, p.currentCardInfo, object : CardListPopupView.ICardListPopupViewListener {
            override fun onClickAddOtherCard() {
                changeToAddOtherCardStatusView()
            }

            override fun onDelete(info: ShangMengCardNoInfo?) {
                p.deleteCard(info)
            }

            override fun onClickItem(info: ShangMengCardNoInfo?) {
                info?.let {
                    p.currentCardInfo = it
                    layoutFirstPay.visibility = View.GONE
                    layoutSecondPay.visibility = View.VISIBLE
                    tvBoundCard.visibility = View.GONE
                    setCardDataView()
                    setNextBtnEnable(true)
                }
            }
        })
        popupDialog = XPopup.Builder(this)
                .moveUpToKeyboard(false) //如果不加这个，评论弹窗会移动到软键盘上面
                .asCustom(cardPopupView)
                .show()
    }

    fun closePopupDialog() {
        popupDialog?.dismiss()
    }

    fun refreshChooseCardDialog() {
        cardPopupView?.updateData(p.cardList, p.currentCardInfo)
    }

    fun hideChooseBoundCardEntrance() {
        tvBoundCard.visibility = View.GONE
    }

    /**
     * 切换成输入新卡状态
     */
    fun changeToAddOtherCardStatusView() {
        p.currentCardInfo = null
        layoutFirstPay.visibility = View.VISIBLE
        layoutSecondPay.visibility = View.GONE
        tvBoundCard.visibility = View.VISIBLE
        etCardNo.setText("")
    }

    /**
     * 进入信用卡界面
     */
    fun toPayPage(
            cardNoData: ShangMengCardNoInfo,
            cardNo: String
    ) {
        //0储蓄卡， 1信用卡
        open(
                if (TextUtils.equals(
                                "0",
                                cardNoData.card_type
                        )
                ) DCPayActivity::class.java else CCPayActivity::class.java,
                mapOf<String, Any>(
                        "cardNoData" to cardNoData,
                        "orderDetail" to if (p.isBuyGood) p.buyGoodShangMengData.order else p.buyMemberShangMengData.order,
                        "cardNo" to cardNo,
                        "secondPay" to p.isSecondPay
                )
                , 2000
        )
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == Activity.RESULT_OK) {
            val intent = Intent()
            if(data != null && data.extras != null  && data.extras.getBoolean("fail" , false)){
                intent.putExtra("fail", true)
            }
            setResult(Activity.RESULT_OK, intent)
            finish()
        }
    }
}